package com.itheima.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.exception.GlobalExceptionHandler;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.PageResult;
import com.itheima.pojo.Student;
import com.itheima.pojo.StudentQueryParam;
import com.itheima.service.ClazzService;
import com.itheima.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {
    @Autowired
    private ClazzService clazzService;

    @Override
    public PageResult paginatedQueries(StudentQueryParam student) {
        Page<Student> studentPage = Page.of(student.getPage(), student.getPageSize());
        Page<Student> page = lambdaQuery().like(StrUtil.isNotBlank(student.getName()), Student::getName, student.getName())
                .eq(ObjectUtil.isNotNull(student.getDegree()), Student::getDegree, student.getDegree())
                .eq(ObjectUtil.isNotNull(student.getClazzId()), Student::getClazzId, student.getClazzId())
                .page(studentPage);
        List<Student> records = page.getRecords();
        records.forEach(s -> {
            Clazz clazz = clazzService.getById(s.getClazzId());
            if (ObjectUtil.isNotNull(clazz)) {
                s.setClazzName(clazz.getName());
            }
        });
        return new PageResult<>(page.getTotal(), page.getRecords());
    }

    @Override
    public void violation(short id, Integer score) {
        //根据id查询出学生信息
        Student student = getById(id);

        //对查询到的学生信息进行赋值
        student.setViolationCount((short) (student.getViolationCount() + 1));
        student.setViolationScore((short) (student.getViolationScore() + score));
        //修改
        updateById(student);
    }


}
